var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var payType = 1; //1:立即支付; 2:提后付款
var isTest = false;
var progressNum = 0; //定义一个初始值0
var quedingShow = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tc: 1,
    util: util,

    screen_h: 480,

    userinfo: {},
    cuid: 0,
    token: '',
    openid: '',

    choosenum: 0,

    wx_address: '',
    address: {},
    ps_address: {},
    zt_address: {},

    goodsinfoArr: [],
    kucun: 0,
    oneprice: 0,

    totalPrice: 0,
    yunfei: '',
    coin: 0.00, //充值余额

    user_jifen: 0,
    use_jf: 0,
    add_jf: 0,

    liuyan: '',

    textarea_w: 300,

    hour: 8,

    hasZitiAddr: false, //是否有自提地址
    ziti: false, //是否自提

    colorSet: '',

    myhao: '',
    payTypeArray: [{
        id: 1,
        title: '线上支付　　  ',
        checked: 'true'
      },
      {
        id: 2,
        title: '货到付款'
      }
    ],
    payTypeXuan: 1,
    ishuiyuan: 0, //是否会员,1是,0不是

    isIphone_x: false,
    nav_bgColor: '#ffffff',

    zongxujifen: 0, //总需积分

    areaArr:'',
    areaIndex: 0,
    areaSelected: '',
    youhuima:'',
    zhekoushow:false,

    hasyhm: false,
    total_youhui:0
  },

  selltype: 0, // 商品购买方式 0:只能花钱买 1:只能用积分换购 2:既要花钱，还要用积分

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      choosenum: options.choosenum,
    });
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", this.data.choosenum);
    var titlename = tc == 1 ? '確認訂單' : '确认订单';
    wx.setNavigationBarTitle({
      title: titlename,
    })

    payType = options.payType == "2" ? 2 : 1;

    wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
          textarea_w: res.windowWidth - 32,
          tc: tc
        });
      }
    });

    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    //获取关于等信息
    app.getAllAbout('contact', function(res) {
      that.setData({
        contact_phone: res
      })
    });


    //读取运费设置信息 
    this.getYunfeiSet();
    
    //可控制每天的可下单时间段
    var date = new Date();
    var hour = date.getHours();

    var g_infoArr = JSON.parse(options.goodsArr);
    console.log("商品信息：", g_infoArr);
    let zkshow = false;
    for(let i = 0; i < g_infoArr.length; i++){
      if (g_infoArr[i].zhekoushow == 0) { //只要有一个是没有折扣价的商品就显示优惠码输入框
          zkshow = true;
          break;
      }
    }
    this.setData({
      goodsinfoArr: g_infoArr,
      hour: hour,
      zhekoushow: zkshow
    })


    // var membercard = wx.getStorageSync('membercard');
    // console.log(membercard);
    // if (membercard) { //会员
    //   this.setData({
    //     ishuiyuan: 1,
    //     payTypeArray: [{
    //       id: 1,
    //       title: '线上支付',
    //       checked: 'true'
    //     }],
    //   })
    // } else {
    //   this.setData({
    //     ishuiyuan: 0,
    //     payTypeArray: [{
    //       id: 2,
    //       title: '货到付款',
    //       checked: 'true'
    //     }],
    //   })
    // }

  },

  //获取运费设置
  getYunfeiSet: function () {
    wx.showLoading({
      title: 'loading',
    });
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        console.log("运费：", responseData);
        var data = responseData.data;
        if (data.res != false) {
          console.log("运费：==1==");
          that.setData({
            areaArr: data,
            areaSelected: data[0]
          })
          that.calTotalPrice();
        }
        that.getLoginInfo();
      },
      fail:function(res){
        wx.hideLoading();
      }
    });
  },

  getLoginInfo: function() {
    var that = this;
    app.getLoginUserInfo(function(res) {
      console.log("mine login:", res);
      
      that.setData({
        cuid: res.uid,
        openid: res.openid,
        token: res.token
      });
      that.getJifen(); //获取积分

      that.getAddress(); //获取地址

      var params = {
        "uid": res.uid,
        "publickey": util.publiccode,
        "ac": "coininfo",
        "privatekey": utilMd5.hexMD5(res.uid + 'coininfo' + res.token)
      };
      console.log("余额参数：uid=" + res.uid + "; token = " + res.token, params);
      util.api({
        method: "post",
        data: params,
        success: function(responseData) {
          console.log("余额返回：", responseData);
          let coinInt = parseInt(responseData.data.coin);
          let coinFloat = parseFloat((coinInt / 100.0).toFixed(2));
          console.log("余额：" + coinInt + "; f = " + coinFloat);
          that.setData({
            coin: coinFloat
          });
        }
      });


      if (res.chongzhi ==1) { //会员
        that.setData({
          ishuiyuan: 1,
          payTypeArray: [{
            id: 1,
            title: '线上支付',
            checked: 'true'
          }],
        })
      } else {
        that.setData({
          ishuiyuan: 0,
          payTypeArray: [{
            id: 2,
            title: '货到付款',
            checked: 'true'
          }],
        })
      }



    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function(e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },

  getJifen: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getusersource",
        "uid": that.data.cuid
      },
      success: function(responseData) {
        console.log("积分", responseData.data)
        that.setData({
          user_jifen: responseData.data.source
        })
      }
    });
  },
  jifenInput: function(e) {
    var that = this;
    var re = /^[0-9]*[0-9]$/i; //校验是否为数字
    var value = e.detail.value;
    if (value == "" || re.test(value)) {
      this.setData({
        use_jf: value
      })
    } else {
      this.setData({
        use_jf: 0
      })
    }

    this.calTotalPrice();
  },


  //判斷是否是100的整数倍
  isNumberBy100: function(ssn) {
    var re = /^[0-9]*[0-9]$/i; //校验是否为数字
    if (re.test(ssn) && ssn % 100 === 0) {
      return true;
    } else {
      return false;
    }
  },

  radioChange: function(e) {
    var that = this;
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    if (e.detail.value == 'zt') {
      this.setData({
        ziti: true,
        address: that.data.zt_address
      })
      console.log('that.data.zt_address：', that.data.zt_address);
    } else {
      this.setData({
        ziti: false,
        address: that.data.ps_address
      })
      console.log('that.data.ps_address：', that.data.ps_address);
    }
    this.calTotalPrice();
  },

  getAddress: function() {

    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getaddress",
        "uid": that.data.cuid,
        "tc": 1
      },
      success: function(responseData) {
        console.log("收货地址：", responseData.data)
        wx.hideLoading();
        if (responseData.data.length > 0) {
          for (var i = 1; i < responseData.data.length; i++) {
            var addrItem = responseData.data[i];
            that.delAddress(addrItem.id);
          }
          if (responseData.data[0].address) {
            //拿到地址最前面两个字
            let areaName = responseData.data[0].address.substring(0, 2);
            for (let i = 0; i < that.data.areaArr.length; i++) {
              if (that.data.areaArr[i].area == areaName) {
                that.setData({
                  areaIndex: i,
                  areaSelected: that.data.areaArr[i]
                });
                responseData.data[0].address = responseData.data[0].address.substring(2);
                that.calTotalPrice();
                break;
              }
            }
          }
          that.setData({
            address: responseData.data[0],
            ps_address: responseData.data[0]
          });
          
        } else {
          //读取微信收货地址
          // if (util.orgid != '16708' && util.orgid != '13078' && util.orgid != '19619') {
          //   that.getWxAddress();

          // }
        }
      }
    });
  },

  //区域切换
  areaPicker: function (e) {
    let index = e.detail.value;
    let sel = this.data.areaArr[index];
    this.setData({
      areaIndex: index,
      areaSelected: sel
    })
    this.calTotalPrice();
  },

  inputNameBlur: function(e) {
    console.log("名字= " + e.detail.value);
    var addr = this.data.address;
    addr.name = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        ps_address: addr
      })

    } else {
      this.setData({
        address: addr,
        zt_address: addr
      })
    }
  },

  inputPhoneBlur: function(e) {
    console.log("联系电话= " + e.detail.value);
    var addr = this.data.address;
    addr.phone = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        // zt_address: addr
      })

    }
  },

  inputAddressBlur: function(e) {
    console.log("地址= " + e.detail.value);
    var addr = this.data.address;
    addr.address = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        // zt_address: addr
      })

    }
  },

  setPSAddress: function(psd_addr) {
    var addr = this.data.address;
    addr.psd_phone = psd_addr.phone;
    addr.address = psd_addr.address + '-' + psd_addr.name;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        ps_address: addr
      })

    } else {
      this.setData({
        address: addr,
        zt_address: addr
      })
    }
  },

  //减少动作
  reduceAction: function(e) {
    var index = e.currentTarget.dataset.itemid;
    var allGwcData = this.data.goodsinfoArr;
    var newInputValue = allGwcData[index].buycount - 1
    if (newInputValue < 1) {
      return;
    }
    allGwcData[index].buycount = newInputValue;
    this.setData({
      goodsinfoArr: allGwcData
    })
    this.calTotalPrice();
  },
  //增加动作
  addAction: function(e) {
    var index = e.currentTarget.dataset.itemid;
    var allGwcData = this.data.goodsinfoArr;
    var newInputValue = allGwcData[index].buycount + 1
    if (newInputValue > allGwcData[index].kucun) {
      wx.showToast({
        title: this.data.tc == 1 ? '超出庫存啦' : '超出库存啦',
      });
      newInputValue = allGwcData[index].kucun;
    }
    allGwcData[index].buycount = newInputValue;
    this.setData({
      goodsinfoArr: allGwcData
    })
    this.calTotalPrice();
  },

  //处理总价
  calTotalPrice: function() {
    var that = this;
    var allData = this.data.goodsinfoArr;
    console.log("allData===", allData);

    var allGoodPrice = 0;
    var cangetJifen = 0; // 本次购买能得到的积分
    var zongxujifen = 0; // 本次购买要消费的积分
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        // if (allData[i].attribute) {
        //   var attribute = allData[i].attribute;
        //   for (var j = 0; j < attribute.length; j++) {
        //     if (attribute[j].attributePrice) {
        //       allGoodPrice += parseInt(attribute[j].attributePrice) * 100;
        //     }
        //   }
        // }
        
        if (allData[i].selltype != '1') {
          if (that.data.ishuiyuan == 1) {
            allGoodPrice += allData[i].memberprice * allData[i].buycount;
          } else {
            allGoodPrice += allData[i].price * allData[i].buycount;
          }
        }

        if (allData[i].selltype != '0') {
          zongxujifen = zongxujifen + parseInt(allData[i].sellscore) * allData[i].buycount;
        }
        // Yunfei += parseInt(allData[i].yunfei) * 100;
        cangetJifen += allData[i].source * allData[i].buycount;
      }
    }

    if (that.data.total_youhui > 0){//计算优惠后的金额
      allGoodPrice -= (that.data.total_youhui * 100);
    }

    var needYunfei = parseInt(this.data.areaSelected.yunfei);
    var myCoin = parseInt(this.data.areaSelected.mianfei);
    if (allGoodPrice / 100 >= myCoin) {
      needYunfei = 0;
    }
    allGoodPrice += (needYunfei * 100);
    //积分抵扣
    if (this.data.use_jf > 0) {
      allGoodPrice -= this.data.use_jf;
    }
    var allPrice = 0;
    if (!this.data.ziti) {
      allPrice = (allGoodPrice / 100.0).toFixed(2);
    }
    if ((this.data.ziti)) {
      allPrice = ((allGoodPrice / 100.0) - needYunfei).toFixed(2);
    }
    allPrice = parseFloat(allPrice);
    this.setData({
      totalPrice: allPrice,
      yunfei: needYunfei,
      add_jf: cangetJifen,
      zongxujifen: zongxujifen,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  liuyanInput: function(e) {
    console.log("留言：" + e.detail.value);
    this.setData({
      liuyan: e.detail.value
    });
  },

  radioChange: function(e) {
    console.log(e);
    this.setData({
      payTypeXuan: e.detail.value
    })
  },

  confirmOrder: function() {
    var that = this;
   
    
    if(that.data.address.phone.length < 11){
      wx.showModal({
          title: '提示',
          content: that.data.tc == 1 ? '手機號必須11位' : '手机号必须11位',
          showCancel: false
        })
        return;
    }
    if (that.data.ishuiyuan == 1){//是会员
      if (that.data.use_jf > that.data.user_jifen) {
        wx.showModal({
          title: '提示',
          content: that.data.tc == 1 ? '您的積分已不足兌換，可每日簽到贏取積分' : '您的积分已不足兑换，可每日签到赢取积分',
          showCancel: false
        })
        return;
      } else {
        if (that.data.payTypeXuan == 1) { //线上支付
          console.log("金额：" + that.data.totalPrice + "; 余额：" + that.data.coin);
          if (that.data.totalPrice > that.data.coin) { //余额不足
            wx.showModal({
              title: '提示',
              content: that.data.tc == 1 ? '您的余額已不足支付，請聯系客服進行充值' : '您的余额已不足支付，请联系客服进行充值',
              showCancel: false
            })
          } else {
            payType = 1;
            that.paygoodsCard();
          }
        } else { //货到付款
          payType = 2;
          that.paygoodsCard();
        }
      }
    } else {
      //货到付款
      payType = 2;
      that.paygoodsCard();
    }
    
  },



  payTypeSelect: function() {
    var that = this;
    console.log("payTypeSelect");
    var payType = 2; //立即支付
    // that.paygoodsCard();

  },


  //下单
  paygoodsCard: function() {
    wx.showLoading({
      title: '',
      mask: true
    })
    var that = this;
    console.log("token:", that.data.token);
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'wxsmallpaycarts' + that.data.token);
    var tc = app.get_tc();
    if (!that.data.address.name) {
      app.dialog(tc == 1 ? '請添加收貨人姓名' : '请添加收货人姓名', 'loading');
      return;
    }
    if (!that.data.address.phone) {
      app.dialog(tc == 1 ? '請添加聯系電話' : '请添加联系电话', 'loading');
      return;
    }
    if (!that.data.address.address) {
      app.dialog(tc == 1 ? '請添加收貨地址' : '请添加收货地址', 'loading');
      return;
    }

    that.saveAddress();
    var cartinfoArr = [];
    var pin = 0;
    for (var i = 0; i < this.data.goodsinfoArr.length; i++) {
      var goodsItem = this.data.goodsinfoArr[i];
      var g_info = {};
      g_info.goods_id = goodsItem.id;
      g_info.goods_name = goodsItem.title;
      g_info.guige = goodsItem.selGuige ? goodsItem.selGuige.id : '';
      g_info.count = goodsItem.buycount;
      g_info.yunfei = goodsItem.yunfei;
      // g_info.coin = goodsItem.price * goodsItem.buycount + g_info.yunfei * 100;
      g_info.coin = goodsItem.price * goodsItem.buycount;
      g_info.linkcode = goodsItem.linkcode;
      cartinfoArr = cartinfoArr.concat(g_info);
      pin = (goodsItem.pin == 1 ? goodsItem.pinzong : 0);
    }
    var data = {
      'cartinfo': JSON.stringify(cartinfoArr),

      'uid': that.data.cuid,
      'type': 'goods',
      'total_fee': payType == 2 ? that.data.totalPrice : 0,
      'allcoin': that.data.totalPrice * 100,
      'del_coin': that.data.totalPrice * 100,
      'consignee': that.data.address.name,
      'phone': that.data.address.phone,
      'addr': that.data.areaSelected.area + that.data.address.address,
      'psd_phone': that.data.address.psd_phone ? that.data.address.psd_phone : '',
      'subject': that.data.tc == 1 ? '購買商品-批量結算' : '购买商品-批量结算',
      'openid': that.data.openid,
      'publickey': util.publiccode,
      'ac': "wxsmallpaycarts",
      'privatekey': privatekey,
      'del_source': that.data.zongxujifen,
      'add_source': that.data.add_jf,
      'message': that.data.liuyan,
      'pin': pin,
      'ziti': that.data.ziti ? 1 : 0,
      'isdraw': payType == 2 ? 1 : 0,
      'booktime': payType == 2 ? '现在就送' : '',
      'ishuiyuan': that.data.ishuiyuan,
      'payType': payType == 2 ? 1 : 0,
      'hyyhcoin':that.data.ishuiyuan == 1 ? that.data.totalPrice * 100 : '', //会员优惠金额
      'yhqcoin':that.data.total_youhui > 0 ? that.data.total_youhui * 100 : '',//优惠券优惠金额
      'yhqnumber':that.data.total_youhui > 0 ? that.data.youhuima : '', //优惠码
      'yunfei':that.data.yunfei  //运费
    };
    console.log("购物车订单参数：", data);
    // return;
    //下单请求
    util.api({
      data: data,
      method: 'POST',
      success: function(responseData) {
        var data = responseData.data;

        console.log("下单返回：", data);
        // that.setData({
        //   out_trade_no: data.out_trade_no
        // })
        // if (isTest) {
        //   that.paytuisong();  
        // }

        wx.hideLoading();
        if (data.res === true) {
          // console.log("payType",payType);
          // if (payType == 2) {
          var result = that.data.tc == 1 ? '下單成功' : '下单成功';
          console.log("下單成功：before======clearGouwuche", data);

          that.clearGouwuche();

          wx.showModal({
            title: '',
            content: result,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
          // } else {
          //   //挂起微信支付请求
          //   var orderData = data.data;
          //   wx.requestPayment(
          //     {
          //       'timeStamp': orderData.timeStamp,
          //       'nonceStr': orderData.nonceStr,
          //       'package': orderData.package,
          //       'signType': orderData.signType,
          //       'paySign': orderData.paySign,
          //       'success': function (res) {
          //         that.paySuccess();
          //       },
          //       'fail': function (res) {
          //         console.log(res);
          //         if (res.errMsg == 'requestPayment:fail cancel') {

          //         } else {
          //           app.dialog(that.data.tc == 1 ? '購買失敗' : '购买失败', 'loading');
          //         }
          //       }
          //     });
          // }


        } else {
          app.dialog(that.data.tc == 1 ? '購買失敗' : '购买失败', 'loading');
        }
      }
    });
  },

  //支付成功处理
  paySuccess: function() {
    var that = this;
    this.clearGouwuche();
    if (this.data.add_jf > 0) {
      var toice = that.data.tc == 1 ? '恭喜你獲得' : "恭喜你获得 " + this.data.add_jf + that.data.tc == 1 ? '積分' : " 积分";
      wx.showModal({
        title: that.data.tc == 1 ? '購買成功' : '购买成功',
        content: toice,
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            var result = that.data.tc == 1 ? '購買成功' : '购买成功';


            // wx.redirectTo({
            //   url: '/pages/order-list/order-list',
            // });
          }
        }
      })
    } else {
      var result = that.data.tc == 1 ? '購買成功' : '购买成功';

      // app.dialogToast('购买成功', 'success', function () {
      //   wx.redirectTo({
      //     url: '/pages/order-list/order-list',
      //   });
      // });
    }
  },



  clearGouwuche: function() {
    
    var gwc_datas = wx.getStorageSync('gwc_datas');
    
    if (gwc_datas && gwc_datas.length > 0) {
      var new_gwc_datas = [];
      for (var i = 0; i < gwc_datas.length; i++) {
        var g_id = gwc_datas[i].id;
        // var guige_id = gwc_datas[i].selGuige ? gwc_datas[i].selGuige.id : '';
        var notPay = true;
        for (var n = this.data.goodsinfoArr.length - 1; n >= 0; n--) {
          var pay_g_id = this.data.goodsinfoArr[n].id;
          // var pay_guige_id = this.data.goodsinfoArr[n].selGuige ? this.data.goodsinfoArr[n].selGuige.id : '';
          // if (g_id == pay_g_id && guige_id == pay_guige_id) {
          console.log("清空购物车：", g_id + "====" + pay_g_id);
          if (g_id == pay_g_id) {
            notPay = false;
            break;
          }
        }
        if (notPay) {
          new_gwc_datas = new_gwc_datas.concat(gwc_datas[i]);
        }
      }
      if (new_gwc_datas.length > 0) {
        // if(payType == 2){
        //   wx.setStorageSync('draw_datas', new_gwc_datas);
        // }else{
        wx.setStorageSync('gwc_datas', new_gwc_datas);
        // }

      } else {
        // if(payType == 2){
        //   wx.removeStorageSync("draw_datas");
        // }else{
        wx.removeStorageSync("gwc_datas");
        // }
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  getWxAddress: function() {
    var that = this;
    wx.chooseAddress({
      success: function(res) {
        // console.log("收货地址：")
        // console.log(res.userName)
        // console.log(res.postalCode)
        // console.log(res.provinceName)
        // console.log(res.cityName)
        // console.log(res.countyName)
        // console.log(res.detailInfo)
        // console.log(res.nationalCode)
        // console.log(res.telNumber)
        var addr = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        that.setData({
          wx_address: res,
          address: {
            name: res.userName,
            phone: res.telNumber,
            address: addr
          }
        });
        that.saveAddress();
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: that.data.tc == 1 ? '獲取通訊地址失敗，這將影響您的使用體驗，是否重新設置授權？' : '获取通讯地址失败，这将影响您的使用体验，是否重新设置授权？',
          showCancel: true,
          cancelText: "否",
          confirmText: "是",
          success: function(res) {
            if (res.confirm) {
              wx.OpenSetting({
                success: function(res) {
                  console.log(res);
                  console.log('success');
                  that.getWxAddress();
                },
                fail: function() {
                  console.log('fail');
                }
              })
            } else if (res.cancel) {
              console.log('用户点击否')
            }
          }
        })
      }
    })
  },

  saveAddress: function() {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "addaddress" + that.data.token);
    util.api({
      data: {
        "privatekey": tmpmd5,
        "ac": "addaddress",
        "uid": that.data.cuid,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "address": that.data.areaSelected.area + that.data.address.address,
        "psd_phone": that.data.address.psd_phone ? that.data.address.psd_phone : '',
        "default": 1
      },
      method: "POST",
      success: function(responseData) {
        that.getAddress();
      }
    });
  },

  delAddress: function(addrId) {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "deladdress" + that.data.token);
    util.api({
      method: "POST",
      data: {
        "privatekey": tmpmd5,
        "ac": "deladdress",
        "uid": that.data.cuid,
        "id": addrId
      },

      success: function(responseData) {
        console.log("删除地址：", responseData);
      }
    });
  },


  //点击确定
  queding: function(e) {
    var that = this;
    wx.redirectTo({
      url: '/pages/order-list/order-list',
    });
    progressNum = 0;
  },
  //支付订单推送
  paytuisong: function() {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "paytuisong" + that.data.token);
    var data = {
      "privatekey": tmpmd5,
      "ac": "paytuisong",
      "uid": that.data.cuid,
      // "cartinfo": JSON.stringify(cartinfoArr),
      "binduid": util.orgid,
      "total_fee": that.data.totalPrice,
      "name": that.data.address.name,
      "phone": that.data.address.phone,
      "address": that.data.areaSelected.area + that.data.address.address,
      'message': that.data.liuyan,

    };

    util.api({
      data: data,
      method: "POST",
      success: function(responseData) {
        console.log("paytuisong===", responseData);
      }
    });
  },
  //下单管理员推送
  xiadantuisong: function() {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "fanhuaxiadantuisong" + that.data.token);
    util.api({
      data: {
        "privatekey": tmpmd5,
        "ac": "fanhuaxiadantuisong",
        "uid": that.data.cuid,
        "binduid": util.orgid,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "btime": that.toDate(new Date().getTime() / 1000),
      },
      method: "POST",
      success: function(responseData) {
        console.log("paytuisong===", responseData);
      }
    });
  },

  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  //时间戳转换时间  
  toDate: function(number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },


  //優惠碼輸入框
  youhuiInput: function(e) {
    var that = this;
    var value = e.detail.value;
    console.log(e);
    this.setData({
      youhuima: value
    })

    if(value.length == 6){
        wx.showLoading({
          title: 'loading...',
        })
        util.api({
          data: {
            "publickey": util.publiccode,
            "ac": "getyouhuima",
            "uid": that.data.cuid,
            "tc": 1,
            "ma": value
          },
          success: function(responseData) {
            wx.hideLoading();
            console.log("优惠码信息：", responseData.data)
            var data = responseData.data;
            if (data.res != false) {
              let shiyong_tiaojian = 0;//订单总额超过这个就可以使用
              if(data.price){
                let chengben = parseFloat(data.chengben);
                shiyong_tiaojian = parseFloat(data.price);
                if (chengben >= 1 && chengben >= shiyong_tiaojian){
                  shiyong_tiaojian = chengben + 0.01;
                }
              }
              
                let kyh_zonge = 0;//可优惠的订单总额
                let youhui_zonge = 0;//已优惠的金额
                let has_youhuima = false;
                var allData = that.data.goodsinfoArr;
                for(var j=0;j<allData.length;j++){
                  if(allData[j].zhekoushow == 0){
                    if (that.data.ishuiyuan == 1){//是会员
                      kyh_zonge += parseFloat(allData[j].memberprice);
                    }else{//非会员
                      kyh_zonge += parseFloat(allData[j].price);
                    }
                  }
                }
              
              if (kyh_zonge / 100 >= shiyong_tiaojian){
                has_youhuima = true;
                if (data.chengben > 0 && data.chengben < 1) {
                  youhui_zonge = kyh_zonge - kyh_zonge * parseFloat(data.chengben);
                } else if (data.chengben >= 1) {
                  youhui_zonge = (data.chengben) * 100;
                }
                that.setData({
                  hasyhm: has_youhuima,
                  total_youhui: (youhui_zonge/100).toFixed(2)
                })
                console.log("计算优惠金额：", that.data.goodsinfoArr);
                that.calTotalPrice();
              } else {
                let toice1 = that.data.tc == 1 ? '訂單總額不足' : '订单总额不足'
                let toice2 = that.data.tc == 1 ? '元，此優惠碼不可使用' : '元，此优惠码不可使用'
                let toiceStr = toice1 + shiyong_tiaojian.toFixed(2) + toice2;
                wx.showModal({
                  title: '',
                  content: toiceStr,
                  showCancel: false
                })
              }
                
            }else{
              wx.showModal({
                title: '提示',
                content: data.msg,
                showCancel: false,
              })
            }
          }
        });
    }else{
      that.setData({
        hasyhm:false,
        total_youhui:0
      })
      that.calTotalPrice();
    }
  },


  dianjiqueding:function(e){
    console.log("aaaaaaaaaaaaaaa");
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['wMTXY1Ejiv6mbKSfpj0yNNoosL2j2RdPkEBbo7OEjzU'],
      success(res) {
        console.log("订阅消息授权结果：", res);
        that.dingdanqueren();
      },
      fail:function(res){
        console.log("fail订阅消息授权结果：", res);
      }
    })
    
  },

  dingdanqueren: function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: that.data.tc == 1 ? '請核對清單是否落單' : '请核对清单是否落单',
      confirmText: that.data.tc == 1 ? '確定' : '确定',

      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.confirmOrder();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }

    })
  }

})